import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

service.interceptors.request.use(config => {
  const { token } = store.state.user
  if (token) {
    config.headers.Authorization = token
  }
  return config
}, error => Promise.reject(error))

service.interceptors.response.use(response => {
  // 检测 Blob 类型
  if (response.data instanceof Blob) {
    return response.data
  }
  // 非 Blob 类型，数据结构
  const { code, msg, data } = response.data
  if (code === 200) {
    // 业务成功

    // 返回数据
    return data
  } else {
    // 业务失败

    // 错误提示
    Message.error(msg || '网络问题、请稍后重试')
    // 返回失败态的Promise实例，携带错误信息
    return Promise.reject(new Error(msg))
  }
}, error => {
  return Promise.reject(error)
})

export default service
